local skynet = require "skynet"
local mysql = require "skynet.db.mysql"

local s = require "service"
local table_utils = require "table_utils"

-- 查询玩家pwd
s.resp.query_player_password = function(source, usnername, password)
    local sql = string.format("select uid, password from users where username=%s", mysql.quote_sql_str(usnername))

    skynet.error("query sql:", sql)
    local res = s.db:query(sql)
    skynet.error("res:" .. table_utils.table2string(res))

    if #res == 0 then
        return false, res
    end

    return true, res[1]
end

-- 查询玩家基本信息
s.resp.query_player_base_info = function(source, usnername, password)
    local sql = string.format("select uid, username, password, nickname, exp, gold, diamond from users where username=%s", mysql.quote_sql_str(usnername))

    skynet.error("query sql:", sql)
    local res = s.db:query(sql)
    skynet.error("res:" .. table_utils.table2string(res))

    if #res == 0 then
        return false, res
    end

    return true, res[1]
end

-- 查询名字是否重复
s.resp.check_username = function(source, username)
    local sql = string.format("select uid from users where username=%s", mysql.quote_sql_str(username))
    skynet.error("check_username query sql:", sql)
    local res = db:query(sql)
    return #res == 0
end

-- 注册
s.resp.register = function(source, username, password)
    local timestamps = os.time()
    local sql = string.format("insert into users(username, password, created, updated) values(%s, %s, %d, %d)",
        mysql.quote_sql_str(username), mysql.quote_sql_str(password), timestamps, timestamps)

    skynet.error("register query sql:", sql)
    local res = db:query(sql)

    if res.err then
        skynet.error("register error:", res.err)
        return false
    else
        return true, res.insert_id
    end
end